<template>
  <div>
    <a-form :form="form" class="form">
      <a-card :bordered="false" title="必填信息" :loading="loading1">
        <a-row class="form-row">
          <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item
              label="用户名(登录账号)"
              has-feedback
              :validate-status="rules.userName.status"
              :help="rules.userName.help"
            >
              <a-input
                @blur="checkUserName('userName')"
                placeholder="请输入用户名"
                v-decorator="[
                  'userName',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入昵称',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
          <!-- { validator: checkUserNameRepeat }, -->

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="密码(登录密码)">
              <a-input
                type="password"
                placeholder="请输入密码"
                v-decorator="[
                  'passWord',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                      },
                      { validator: checkPassWord },
                      { min: 6, message: '不得少于6个字符' },
                      { max: 20, message: '不得超过20个字符' },
                    ],
                  },
                ]"
              />
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="昵称">
              <a-input
                placeholder="请输入昵称"
                v-decorator="[
                  'nickName',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入昵称',
                      },
                      { max: 255, message: '不得超过255个字符' },
                    ],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row class="form-row">
          <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item label="真实姓名">
              <a-input
                placeholder="请输入真实姓名"
                v-decorator="[
                  'realName',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入真实姓名',
                      },
                      { max: 255, message: '不得超过255个字符' },
                    ],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="选择权限">
              <a-select
                :showSearch="true"
                optionFilterProp="label"
                placeholder="请选择权限"
                v-decorator="[
                  'roleId',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请选择权限',
                      },
                    ],
                    initialValue: -1,
                  },
                ]"
              >
                <a-select-option
                  :value="item.id"
                  v-for="(item, index) in adminRoleList"
                  :key="index"
                  :label="item.name"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="状态">
              <!-- <a-switch
                checked-children="启用"
                un-checked-children="禁用"
                default-checked
                  v-decorator="['status',{valuePropName: 'checked',initialValue:true}]"
              /> -->
              <a-switch
                checked-children="启用"
                un-checked-children="禁用"
                v-decorator="[
                  'status',
                  { valuePropName: 'checked', initialValue: true },
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <a-card
        class="card"
        :title="'CRM系统'"
        :bordered="false"
        :loading="treeDataLoading || crmRoleList.loading"
        style="margin-top: 20px"
      >
        <a-row class="form-row">
          <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item label="所属部门">
              <a-tree-select
                show-search
                style="width: 100%"
                :treeData="treeData"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                treeNodeFilterProp="title"
                placeholder="请选择所属部门"
                allow-clear
                tree-default-expand-all
                :replaceFields="{
                  title: 'name',
                  key: 'id',
                  value: 'id',
                }"
                v-decorator="[
                  'division_id',
                  {
                    initialValue: undefined,
                  },
                ]"
              >
                <!-- <a-icon slot="suffixIcon" type="smile" /> -->
              </a-tree-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <a-card
        class="card"
        :title="'选填信息'"
        :bordered="false"
        style="margin-top: 20px"
      >
        <a-row class="form-row">
          <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item label="电话">
              <a-input
                placeholder="请输入电话"
                v-decorator="[
                  'phone',
                  {
                    rules: [
                      { max: 255, message: '不得超过255个字符' },
                      { validator: checkPhone },
                    ],
                  },
                ]"
              />
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="邮箱">
              <a-input
                placeholder="请输入邮箱"
                v-decorator="[
                  'email',
                  {
                    rules: [
                      { max: 255, message: '不得超过255个字符' },
                      { type: 'email', message: '必须为邮箱格式' },
                    ],
                  },
                ]"
              />
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="生日">
              <a-date-picker
                style="width: 100%"
                placeholder="请选择日期"
                v-decorator="[
                  'birthday',
                  {
                    rules: [],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row class="form-row">
          <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item label="头像">
              <!-- <div class="portraitShow" @click="setPortrait()">
                <a-icon class="plus-icon" type="plus" v-show="!readerResult" />

                <input
                  type="file"
                  id="portrait"
                  style="display: none"
                  title=""
                  @change="portraitChange"
                />
                <div class="portraitImage" v-show="readerResult">
                  <img style="width: 100%; height: 100%" :src="readerResult" />
                </div>
              </div> -->
              <OneImage ref="oneImage" />
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="性别">
              <a-radio-group
                name="sex"
                v-decorator="[
                  'sex',
                  {
                    rules: [{ max: 255, message: '不得超过255个字符' }],
                    initialValue: `未知`,
                  },
                ]"
              >
                <a-radio :value="`男`"> 男 </a-radio>
                <a-radio :value="`女`"> 女 </a-radio>
                <a-radio :value="`未知`"> 未知 </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="详细地址">
              <a-input
                type="textarea"
                v-decorator="['belongs', {}]"
                placeholder="详细地址"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <footer-tool-bar>
        <a-button type="primary" @click="validate" :loading="loading2"
          >提交</a-button
        >
      </footer-tool-bar>
    </a-form>
  </div>
</template>

<script>
import { adminRoleList, adminAdd, adminAvatar } from "@/services/admin";
// import { crmRoleSelectList } from "@/services/crmRole"
// import FormEdit from "@/components/form/FormEdit";
import FooterToolBar from "@/components/tool/FooterToolBar";
import OneImage from "@/components/uploadImages/oneImage";
import { divisionList } from "@/services/division";
// import TestClose from '@/utils/test'
// import TestClose from '@/main'

// let checkUserNameRepeat = async (rule, value, callback) => {
//   // clearTimeout(checkPending);

//   if (typeof value != "string" || value == "") {
//     return callback();
//   }

//   let res = await checkUserName({ userName: value });
//   if (res.code == 200) {
//     return callback();
//   } else {
//     return callback(new Error(res.message));
//   }
// };

export default {
  name: "AdminAdd",
  //   i18n: require('../i18n'),
  components: {
    // CollectionCreateForm: CollectionCreateForm,
    FooterToolBar: FooterToolBar,
    OneImage: OneImage,
    // FormEdit: FormEdit,
  },
  data() {
    return {
      //   phoneMessageColumns: phoneMessageColumns,
      //   annalsPhoneColumn: annalsPhoneColumn,
      //   annalsEmailColumn: annalsEmailColumn,
      // phoneMessage: [],
      // dataSource:dataSource,
      // columns:columns,
      //   groupList: [],
      form: this.$form.createForm(this),

      //   visible: false,
      adminRoleList: [],
      treeData: [],
      rules: {
        userName: {
          status: "",
          help: "",
        },
      },
      readerResult: "",
      loading1: false,
      loading2: false, //提交
      treeDataLoading: false,
      crmRoleList: {
        data: [],
        loading: false,
      },
      keys: 0,
      title: "",
    };
  },
  created() {
    // this.closeTabs.$emit('test','msg');
    this.adminRoleListLoad();
    this.divisionListLoad();
    // this.crmRoleSelectListLoad()
  },
  watch: {},
  methods: {
    async validate() {
      const { form, $message, $router, $refs, rules, fmtDate } = this;
      let this_ = this;

      this.checkUserName("userName");

      form.validateFields((err) => {
        if (err || rules.userName.status != "success") {
          $message.error("信息填写有误");
          return;
        } else {
          this.$confirm({
            title: "确定要添加吗?",
            async onOk() {
              this_.loading2 = true;
              let formData = form.getFieldsValue();
              let fileData = $refs.oneImage.getFile();
              if (fileData.has("file")) {
                if (!fileData.get("file")) {
                  formData["avatar"] = "";
                } else {
                  let fileRes = await adminAvatar(fileData);
                  if (fileRes.code == 200) {
                    formData["avatar"] = fileRes.data.url;
                  } else {
                    return;
                  }
                }
              }
              if (formData["birthday"])
                formData["birthday"] = fmtDate(formData["birthday"]);
              let res = await adminAdd({ formData });
              if (res.code == 200) {
                $message.success(res.message);
                this_.closeTabs.$emit("closeTabs");
                $router.push("/personnelManagement/adminList");
              } else if (res.code == 100 && res.message == "该用户名已存在") {
                rules["userName"].status = "error";
                rules["userName"].help = res.message;
              }
              this_.loading2 = false;
            },
          });
        }
      });
    },
    async divisionListLoad() {
      this.treeDataLoading = true;
      let res = await divisionList({
        keyWord: { "equal-crm_division-status": 1 },
      });
      if (res.code == 200) {
        this.treeData = res.data.list;
      }
      this.treeDataLoading = false;
    },
    async adminRoleListLoad() {
      this.loading1 = true;
      let res = await adminRoleList({ selectOrId: "", field: ["id", "name"] });
      if (res.code == 200) {
        this.adminRoleList = res.data;
      }
      this.adminRoleList.unshift({ id: -1, name: "无权限" });
      this.loading1 = false;
    },
    // async crmRoleSelectListLoad(){
    //      this.crmRoleList.loading = true
    //      let res =  await crmRoleSelectList()
    //      if(res.code == 200){
    //         const {list} = res.data
    //         this.crmRoleList.data = list
    //      }
    //      this.crmRoleList.data.unshift({'id':0,'name':'超级管理员(拥有所有权限)'})
    //      this.crmRoleList.loading = false
    // },
    checkUserName(key) {
      this.rules[key].status = "validating";
      let field = this.form.getFieldValue(key);
      if (!field || field.trim() == "") {
        this.rules[key].status = "error";
        this.rules[key].help = "请输入用户名";
        return;
      } else if (field.length < 5) {
        this.rules[key].status = "error";
        this.rules[key].help = "不得少于5个字符";
        return;
      } else if (new RegExp("[^\\w]").test(field)) {
        this.rules[key].status = "error";
        this.rules[key].help = "用户名只能由字母数字下划线组成";
        return;
      } else if (field.length > 20) {
        this.rules[key].status = "error";
        this.rules[key].help = "不得超过20个字符";
        return;
      }
      this.rules[key].status = "success";
      this.rules[key].help = "";
    },
  },
};
</script>

<style scoped lang="less">
.aSelect {
  display: flex;
  width: 100%;
  justify-content: space-between;
  /* border: 1px solid red; */
  align-items: center;
}

.card {
  margin-bottom: 24px;
}

.form {
  .form-row {
    margin: 0 -8px;
    // display: flex;
    // justify-content: space-between;
    //    display: flex;
    // justify-content: space-between;
  }
  .ant-col-md-12,
  .ant-col-sm-24,
  .ant-col-lg-6,
  .ant-col-lg-8,
  .ant-col-lg-10,
  .ant-col-xl-8,
  .ant-col-xl-6 {
    padding: 0 8px;
  }
}
.topRow button {
  margin-top: 5px;
  margin-left: 10px;
}
</style>
